<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
class Parameterlogic{

	/**
     * 参数列表
     * @param  int $user_id  操作用户ID
     * @param  string $title  标题搜索
     * @author shiqiang
     * @return mixed
     */
    public function index($user_id, $title = '', $code = ''){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'title' 	=> $title,
				'code' 		=> $code,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/

            $map = [];//搜索处理
            if($title != '') $map[] = ['title', 'like', '%'. $title .'%'];
			if($code != '')  $map[] = ['code', 'like', '%'. $code .'%'];
			$list = model('ErpParameter', 'model') -> where($map) -> order('sort asc, create_time desc') -> paginate();
			
			$rel_list = [];
            foreach($list as $key => $value){
                $attribute_list = model('ErpParameterAttribute', 'model') -> where('pid', $value['id']) -> order('sort asc') -> column('id,title,sort');
                $attribute = [];
                foreach($attribute_list as $key1 => $value1){
                    $attribute_info['attributeId'] = $value1['id'];
                    $attribute_info['title'] = $value1['title'];
                    $attribute_info['sort']  = $value1['sort'];
                    $attribute[] = $attribute_info;
                }
            
				$rel_list[$key]['id'] 			= (int)$value['id'];
				$rel_list[$key]['title'] 		= (string)$value['title'];
				$rel_list[$key]['sort'] 		= (int)$value['sort'];
				$rel_list[$key]['code'] 		= (string)$value['code'];
                $rel_list[$key]['createTime'] 	= (int)$value['create_time'];
                $rel_list[$key]['attribute']    = (array)$attribute;
			}
			$result_list = [];
			$result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
			$result_list['data'] 			= $rel_list;

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 添加
     * @param  int    $user_id   操作用户ID
     * @param  string $title  	 标题
     * @param  int    $sort  	 排序
     * @param  string $code  	 编码
     * @param  array $attribute  属性
     * @author shiqiang
     * @return mixed
     */
    public function add($user_id, $title, $sort, $code, $attribute){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'title' 	=> $title,
				'sort' 		=> $sort,
				'code' 		=> $code,
				'attribute' => $attribute,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpParameter') -> addData($title, $sort, $code);//添加
			if($rel['code'] < 0){
				DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
			}
			$pid = $rel['data'];
			foreach($attribute as $key => $value){//插入属性
				$rel = model('ErpParameterAttribute') -> addData($value['title'], $value['sort'], $pid);
				if($rel['code'] < 0){
					DB::rollback();
					return array_out(-1005, 'error');//添加失败 返回-1005,error
				}
			}

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 编辑
     * @param  int    $user_id   操作用户ID
     * @param  int    $id  		 参数id
     * @param  string $title  	 标题
     * @param  int    $sort  	 排序
     * @param  string $code  	 编码
	 * @param  array $attribute  属性
     * @author shiqiang
     * @return mixed
     */
    public function edit($user_id, $id, $title, $sort, $code, $attribute){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
				'title' 	=> $title,
				'sort' 		=> $sort,
				'code' 		=> $code,
				'attribute' => $attribute,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpParameter') -> editData($id, $title, $sort, $code);
			if($rel['code'] < 0){
				DB::rollback();
                return array_out(-1005, 'error');//编辑失败 返回-1005,error
			}
			$attribute_id = model('ErpParameterAttribute') -> where('pid', $id) -> column('id');//原有的属性
			if(!empty($attribute_id)){
				$rel = model('ErpParameterAttribute') -> deleteData($attribute_id);//删除
				if($rel['code'] < 0){
					DB::rollback();
					return array_out(-1005, 'error2');//属性删除失败 返回-1005,error
				}
			}
			foreach($attribute as $key => $value){//插入属性
				$rel = model('ErpParameterAttribute') -> addData($value['title'], $value['sort'], $id);
				if($rel['code'] < 0){
					DB::rollback();
					return array_out(-1005, 'error');//属性添加失败 返回-1005,error
				}
			}

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 删除
     * @param  int    $user_id   操作用户ID
     * @param  int    $id  		参数id
     * @author shiqiang
     * @return mixed
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$parameter_childs = model('ErpParameterAttribute') -> where('pid',$id) -> column('id'); // 获取参数下属性
			
			$rel = model('ErpParameter') -> deleteData($id);
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			if(!empty($parameter_childs)){
				$rel = model('ErpParameterAttribute') -> deleteData($parameter_childs);
				if($rel['code'] < 0){
					return array_out(-1005, 'error2');//删除失败 返回-1005,error
				}
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 参数详情
     * @param  int    $user_id   操作用户ID
     * @param  int    $id  		参数id
     * @author shiqiang
     * @return mixed
     */
	public function details($user_id, $id){
		DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$info = model('ErpParameter', 'model') -> where('id', $id) -> find();
			$rel_list = [];
			$rel_list['id'] 		= (int)$info['id'];
			$rel_list['title'] 		= (string)$info['title'];
			$rel_list['sort'] 		= (int)$info['sort'];
			$rel_list['code'] 		= (string)$info['code'];
			$rel_list['createTime'] = (int)$info['create_time'];
			
			$attribute_list = model('ErpParameterAttribute', 'model') -> where('pid', $id) -> order('sort asc') -> column('id,title,sort');
			$attribute = [];
			foreach($attribute_list as $key => $value){
				$attribute_info['attributeId'] = $value['id'];
				$attribute_info['title'] = $value['title'];
				$attribute_info['sort']  = $value['sort'];
				$attribute[] = $attribute_info;
			}
			$rel_list['attribute'] = (array)$attribute;
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
}